<template>
  <el-dialog title="修改密码" :visible.sync="visible" @closed="clearData">
    <el-form :model="formData" :rules="rules" label-position="right" label-width="80px" ref="formData">
      <el-form-item label="用户名" prop="username">
        <el-input placeholder="用户名" v-model="formData.username" auto-complete="off" readonly/>
      </el-form-item>
      <el-form-item label="原密码" prop="oldPassword">
        <el-input placeholder="原密码" show-password v-model="formData.oldPassword"/>
      </el-form-item>
      <el-form-item label="新密码" prop="password">
        <el-input placeholder="新密码" show-password v-model="formData.password"/>
      </el-form-item>
      <el-form-item label="确认密码" prop="resPassword">
        <el-input placeholder="确认密码" show-password v-model="formData.resPassword"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm">提交</el-button>
        <el-button type="warning" @click="visible = false">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script>
const initData = {
  username: '',
  password: '',
  oldPassword: '',
  resPassword: ''
}
export default {
  name: 'UserinfoUpdate',
  data () {
    return {
      formData: { ...initData },
      rules: {
        oldPassword: [{
          required: true,
          message: '原密码不能为空',
          trigger: 'blur'
        }],
        password: [{
          required: true,
          message: '新密码不能为空',
          trigger: 'blur'
        }],
        resPassword: [
          {
            required: true,
            message: '确认密码不能为空',
            trigger: 'blur'
          },
          {
            validator: (rule, value, cb) => {
              if (value === this.formData.password) {
                cb()
              } else {
                cb(new Error('两次密码不一致'))
              }
            },
            trigger: 'blur'
          }
        ]
      },
      visible: false
    }
  },
  methods: {
    submitForm () {
      this.$refs.formData.validate(validate => {
        if (validate) {
          this.$http.post('user/password', this.formData, true).then(() => {
            this.$message.success('修改密码成功，请重新登录')
            this.visible = false
            this.$emit('closeWin')
          })
        }
      })
    },
    init (username) {
      this.visible = true
      this.formData.username = username
    },
    clearData () {
      this.formData = { ...initData }
      this.photoList = []
      this.$refs.formData.resetFields()
    }
  }
}
</script>

<style scoped>

</style>
